<template>
  <section class="todoapp">
    <!-- 头部部分 -->
    <TodoHeader @addTask="hAddTask" />
    <TodoMain
    @changeAll="hChangeAll" 
    @changeDone="hChangeDone" 
    @DelTask="DelTask" 
    :list="showList" />
    <TodoFooter 
    @changType="hChangeType" 
    @clearDone="hClearDone" 
    :list="showList" />

    <!-- 主体部分 -->
    

    <!-- 底部部分 -->
    
  </section>
</template>

<script>
import TodoHeader from './components/TodoHeader.vue'
import TodoMain from './components/TodoMain.vue'
import TodoFooter from './components/TodoFooter.vue'
export default {
  components:{
    TodoHeader,TodoMain,TodoFooter
  },
  data () {
  return {
  //  list: [
  //       { id: 1, name: '吃饭', isDone: true },
  //       { id: 2, name: '睡觉', isDone: false },
  //       { id: 3, name: '打豆豆', isDone: true }
  //     ],
    list: JSON.parse(localStorage.getItem('list') || '[]'),
    type:'all'
  };
},
methods:{
  DelTask(id){
    const index = this.list.findIndex(item => item.id === id)
    this.list.splice(index,1)
  },
  hChangeDone(id){
    const obj = this.list.find(item => item.id === id)
    obj.isDone = !obj.isDone

  },
  hAddTask(taskname){
    this.list.push({
      id:Date.now,
      name:taskname,
      isDone:false
    })

  },
  hClearDone(){
    this.list = this.list.filter(item => !item.isDone)
  },
  hChangeType(type) {
    this.type = type
  },
  hChangeAll(val) {
    this.list.forEach(item => item.isDone = val)
  }

},
computed:{
  showList() {
    if(this.type === 'all'){
      return this.list
    } else if(this.type === 'active'){
      return this.list.filter(item => !item.isDone)
    } else if(this.type === 'completed'){
      return this.list.filter(item => item.isDone)
    } 
  }
},
watch: {
    // 数组, 所以需要用深度侦听
    list: {
      deep: true,
      handler() {
        // 将 list 存储到本地
        localStorage.setItem('list', JSON.stringify(this.list))
      }
    }
  }
}
</script>

<style></style>
